
package cup.modules.auth.granter;

import cup.common.cache.CacheNames;
import cup.modules.auth.provider.ITokenGranter;
import cup.modules.auth.provider.TokenParameter;
import lombok.AllArgsConstructor;
import cup.core.log.exception.ServiceException;
import cup.core.redis.cache.CupRedis;
import cup.core.tool.utils.DigestUtil;
import cup.core.tool.utils.Func;
import cup.core.tool.utils.WebUtil;
import cup.modules.auth.enums.UserEnum;
import cup.modules.auth.utils.TokenUtil;
import cup.modules.system.entity.Tenant;
import cup.modules.system.entity.UserInfo;
import cup.modules.system.service.IRoleService;
import cup.modules.system.service.ITenantService;
import cup.modules.system.service.IUserService;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.Duration;
import java.util.List;

/**
 * 账号密码验证
 */
@Component
@AllArgsConstructor
public class PasswordTokenGranter implements ITokenGranter {

	public static final String GRANT_TYPE = "password";
	public static final Integer FAIL_COUNT = 5;

	private final IUserService userService;
	private final IRoleService roleService;
	private final ITenantService tenantService;
	private final CupRedis cupRedis;

	@Override
	public UserInfo grant(TokenParameter tokenParameter) {
		HttpServletRequest request = WebUtil.getRequest();
		// 获取用户绑定ID
		String headerDept = request.getHeader(TokenUtil.DEPT_HEADER_KEY);
		String headerRole = request.getHeader(TokenUtil.ROLE_HEADER_KEY);

		// 获取用户信息
		String tenantId = tokenParameter.getArgs().getStr("tenantId");
		String username = tokenParameter.getArgs().getStr("username");
		String password = tokenParameter.getArgs().getStr("password");

		// 判断登录是否锁定
		// TODO 2.8.3版本将增加：1.参数管理读取配置 2.用户管理增加解封按钮
		int cnt = Func.toInt(cupRedis.get(CacheNames.tenantKey(tenantId, CacheNames.USER_FAIL_KEY, username)), 0);
//		if (cnt >= FAIL_COUNT) {
//			throw new ServiceException(TokenUtil.USER_HAS_TOO_MANY_FAILS);
//		}

		UserInfo userInfo = null;
		if (Func.isNoneBlank(username, password)) {
			// 获取租户信息
			Tenant tenant = tenantService.getByTenantId(tenantId);
			if (TokenUtil.judgeTenant(tenant)) {
				throw new ServiceException(TokenUtil.USER_HAS_NO_TENANT_PERMISSION);
			}
			// 获取用户类型
			String userType = tokenParameter.getArgs().getStr("userType");
			// 根据不同用户类型调用对应的接口返回数据，用户可自行拓展
			if (userType.equals(UserEnum.WEB.getName())) {
				userInfo = userService.userInfo(tenantId, username, DigestUtil.hex(password), UserEnum.WEB);
			} else if (userType.equals(UserEnum.APP.getName())) {
				userInfo = userService.userInfo(tenantId, username, DigestUtil.hex(password), UserEnum.APP);
			} else {
				userInfo = userService.userInfo(tenantId, username, DigestUtil.hex(password), UserEnum.OTHER);
			}
		}
		// 错误次数锁定
		if (userInfo == null || userInfo.getUser() == null) {
			cupRedis.setEx(CacheNames.tenantKey(tenantId, CacheNames.USER_FAIL_KEY, username), cnt + 1, Duration.ofMinutes(30));
		}
		// 多部门情况下指定单部门
		if (Func.isNotEmpty(headerDept) && userInfo != null && userInfo.getUser().getDeptId().contains(headerDept)) {
			userInfo.getUser().setDeptId(headerDept);
		}
		// 多角色情况下指定单角色
		if (Func.isNotEmpty(headerRole) && userInfo != null && userInfo.getUser().getRoleId().contains(headerRole)) {
			List<String> roleAliases = roleService.getRoleAliases(headerRole);
			userInfo.setRoles(roleAliases);
			userInfo.getUser().setRoleId(headerRole);
		}
		return userInfo;
	}

}
